#import "HHSinglePickerView.h"

#import <BCUIKit/UIView+BCHelper.h>
#import <BCFoundation/BCFoundationUtils.h>
#import <BCComConfigKit/BCComConfigKit.h>
#import "BCFoundation.h"
#import "Masonry.h"

#define kHHSinglePickerView_PickH     200
#define kHHSinglePickerView_PickBarH  44

@interface HHSinglePickerView ()<UIPickerViewDataSource,UIPickerViewDelegate>
/// 父view，默认 keyWindow
@property (nonatomic, weak, nullable) UIView *containerView;
@property (nonatomic, strong) UIView *contactView;
@property (nonatomic, strong, readwrite) UIPickerView *pickerView;
@property (nonatomic, strong, readwrite) UIButton *doneButton;
@property (nonatomic, strong, readwrite) UIButton *cancelButton;
@end

@implementation HHSinglePickerView
//MARK: - system
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self configSubViews];
    }
    return self;
}
- (void)dealloc {
#ifdef DEBUG
    NSLog(@"HHSinglePickerView dealloc");
#endif
}

//MARK: - 显示
+ (instancetype )zh_pickerInView:(UIView *)view withData:(NSArray<HHOptionsObject *>*)dataArr completion:(void(^)(HHOptionsObject *optionsObject))completion {
    if (!view) {
        view = [UIApplication sharedApplication].delegate.window;
    }
    HHSinglePickerView *pickerView = [[HHSinglePickerView alloc] initWithFrame:view.bounds];
    pickerView.doneBlock = completion;
    pickerView.dataArr = dataArr;
    if (view) {
        pickerView.containerView = view;
    }
    return pickerView;
}
+ (instancetype )zh_showPickerInView:(UIView *)view withData:(NSArray<HHOptionsObject *>*)dataArr completion:(void(^)(HHOptionsObject *optionsObject))completion {
    if (!view) {
        view = [UIApplication sharedApplication].delegate.window;
    }
    HHSinglePickerView *pickerView = [[HHSinglePickerView alloc] initWithFrame:view.bounds];
    pickerView.doneBlock = completion;
    pickerView.dataArr = dataArr;
    if (view) {
        pickerView.containerView = view;
    }
    [pickerView.containerView addSubview:pickerView];
    [pickerView showAnimtion];
    return pickerView;
}
- (void)showAnimtion {
    if (self.superview == nil) {
        [self.containerView addSubview:self];
    }
    self.hidden = false;
    [UIView animateWithDuration:0.25f animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.3];
        [self.contactView setBc_y:(self.bc_bottom-kHHSinglePickerView_PickH-kHHSinglePickerView_PickBarH)];
    }];
}
- (void)hideAnimation {
    if (self.hidden) {
        return ;
    }
    [UIView animateWithDuration:0.25f animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0];
        [self.contactView setBc_y:self.bc_bottom];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        self.hidden = true;
    }];
}


//MARK: - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.dataArr.count;
}

//MARK: - UIPickerViewDelegate
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return self.rowHeight > 0 ? self.rowHeight : 30;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    HHOptionsObject *optionObj = [self.dataArr objectAtIndex:row];
    return optionObj.displaytext;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

}

//MARK: - Event Response
- (void)cancel {
    [self hideAnimation];
}
- (void)done {
    NSInteger index = [self.pickerView selectedRowInComponent:0];
    HHOptionsObject *optionObj = [self.dataArr objectAtIndex:index];
    if (self.doneBlock) {
        self.doneBlock(optionObj);
    }
    [self hideAnimation];
}

//MARK: - Subviews
- (void)configSubViews {
    self.hidden = true;
    self.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0];
    _contactView = ({
        UIView *contactView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bc_bottom, kBCSCREEN_WIDTH, 244)];
        contactView.backgroundColor = [UIColor whiteColor];
        [self addSubview:contactView];
        contactView;
    });
    _pickerView = ({
        UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, kBCSCREEN_WIDTH, 200)];
        picker.dataSource = self;
        picker.delegate = self;
        [_contactView addSubview:picker];
        picker;
    });
    
    //add tool bar
    UIView *buttonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kBCSCREEN_WIDTH, kHHSinglePickerView_PickBarH)];
    buttonView.backgroundColor = [UIColor bc_colorWithRGB:0xF4F4F4];
    [self.contactView addSubview:buttonView];
 
    [buttonView addSubview:self.cancelButton];
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.offset(0);
        make.width.mas_equalTo(60);
    }];
    
    [buttonView addSubview:self.doneButton];
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.offset(0);
        make.width.mas_equalTo(60);
    }];
}
- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _cancelButton.titleLabel.font = kBCFont(15);
        [_cancelButton setTitle:BCLOC(@"取消") forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[UIColor bc_colorWithRGB:0x4A90E2] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}
- (UIButton *)doneButton {
    if (!_doneButton) {
        _doneButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _doneButton.titleLabel.font = kBCFont(15);
        [_doneButton setTitle:BCLOC(@"确定") forState:UIControlStateNormal];
        [_doneButton setTitleColor:[UIColor bc_colorWithRGB:0x4A90E2] forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];

    }
    return _doneButton;
}
- (void)setDataArr:(NSArray *)dataArr {
    _dataArr = dataArr;
    [self.pickerView reloadComponent:0];
}
- (void)setRowHeight:(CGFloat)rowHeight {
    _rowHeight = rowHeight;
    [self.pickerView reloadComponent:0];
}
- (void)setLastOptionsObject:(HHOptionsObject *)lastOptionsObject {
    if (!lastOptionsObject) return;
    /// 根据formValue和displaytext来匹配
    __block NSInteger index = 0;
    [self.dataArr enumerateObjectsUsingBlock:^(HHOptionsObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.formValue isEqual:lastOptionsObject.formValue] &&
            [obj.displaytext isEqualToString:lastOptionsObject.displaytext]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index < self.dataArr.count) {
        [self.pickerView selectRow:index inComponent:0 animated:NO];
    }
}

//MARK: - Event
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [touches.anyObject locationInView:self];
    if (point.y < self.bc_height - kHHSinglePickerView_PickH - kHHSinglePickerView_PickBarH) {
        [self hideAnimation];
    }
}

@end

//MARK: -
//MARK: - HHOptionsObject
@implementation HHOptionsObject

+(HHOptionsObject *)optionsObjectWithValue:(id)value displayText:(NSString *)displayText {
    HHOptionsObject *optionsObject = [[HHOptionsObject alloc] init];
    optionsObject.formValue = value;
    optionsObject.displaytext = displayText;
    return optionsObject;
}

//MARK: - NSCoding
-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.formValue
                   forKey:@"formValue"];
    [encoder encodeObject:self.displaytext
                   forKey:@"displaytext"];
}

-(instancetype)initWithCoder:(NSCoder *)decoder {
    if ((self=[super init])) {
        [self setValue:[decoder decodeObjectForKey:@"formValue"]
                forKey:@"formValue"];
        [self setValue:[decoder decodeObjectForKey:@"displaytext"]
                forKey:@"displaytext"];
    }
    return self;
}

@end
